#include "WaveformChart.h"
#include "QVBoxLayout"
#include "QColorDialog"
#include "QDateTimeAxis"
#include "QDateTime"
// #include "customtimevalueaxis.h"
#include <QToolTip>

WaveformChart::WaveformChart(int SampleRate,int seriesNum,QWidget *parent) :
    QChartView(parent),
    _SampleRate(SampleRate),
    _seriesNum(seriesNum){
    // 初始化布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    QHBoxLayout *layout_h = new QHBoxLayout(this);

    // 初始化图表
    chart = new QChart();
    series = new QLineSeries(this);
    series->setUseOpenGL(true);
    series_f1=new QLineSeries(this);
    series_f2=new QLineSeries(this);


    chart->addSeries(series);
    if(_seriesNum==2)
        chart->addSeries(series_f1);
    if(_seriesNum==3){
        chart->addSeries(series_f1);
        chart->addSeries(series_f2);
    }



    maxv=-10000;
    minv=10000;
    SampleNum=0;
    // 设置轴范围
    xAxis = new QValueAxis(this);
    yAxis = new QValueAxis(this);
    xAxis->setRange(0, _SampleRate*10);//显示10秒数据
    // 设置图表标题和轴标签
    // chart->setTitle("脉搏波");
    chart->addAxis(xAxis, Qt::AlignBottom);
    chart->addAxis(yAxis, Qt::AlignLeft);
    xAxis->setTitleText("Samples");
    yAxis->setTitleText("Amplitude");
    series->attachAxis(xAxis);
    series->attachAxis(yAxis);
    // 初始化图表视图
    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    //初始化恢复按钮
    bt_full=new QPushButton(this);
    bt_full->setText("全程波形");
    connect(bt_full, &QPushButton::clicked, this, &WaveformChart::onclicked);

    // 在构造函数中初始化颜色选择按钮
    colorButton = new QPushButton("选择颜色", this);
    connect(colorButton, &QPushButton::clicked, this, &WaveformChart::onColorButtonClicked);
    // 初始化滚动条
    scrollBar = new QScrollBar(Qt::Horizontal, this);
    scrollBar->resize(100,100);
    scrollBar->setVisible(true);
    connect(scrollBar, &QScrollBar::valueChanged, this, &WaveformChart::onScrollBarValueChanged);
    layout_h->addWidget(bt_full,1);
    layout_h->addWidget(colorButton,1);
    layout_h->addWidget(scrollBar,10);

    // 初始化矩形框
    rubberBand = new QRubberBand(QRubberBand::Rectangle, chartView);

    // 将图表视图和滚动条添加到布局
    layout->addWidget(chartView,3);
    layout->addLayout(layout_h,1);

    // 设置布局
    setLayout(layout);

    // 安装事件过滤器
    chartView->viewport()->installEventFilter(this);
}

WaveformChart::~WaveformChart()
{
    qDebug()<<"~WaveformChart()";
}

void WaveformChart::setSerialNames(QString name1,QString name2,QString name3)
{
    series->setName(name1);
    series_f1->setName(name2);
    series_f2->setName(name3);
}
void WaveformChart::addDataPoints(QList<QPointF> &points)
{
    int len=points.size();
    xAxis->setRange(0,len);
    scrollBar->setRange(0, len-_SampleRate*10);
    scrollBar->setValue(0);
    series->append(points);
    chart->update();
}
// 添加数据点
void WaveformChart::addDataPoint(double x, double y) {
    SampleNum++;
    if(maxv<y)
        maxv=y;
    if(minv>y)
        minv=y;
    if(SampleNum%_SampleRate==0)
    {
        // chart->update();
        yAxis->setRange(minv-fabs(minv)/10, maxv+fabs(maxv)/10);
    }
    // qDebug()<<"SampleNum="<<SampleNum;
    series->append(x, y);
    // chart->update();
    scrollBar->setRange(0, SampleNum-_SampleRate*10);
    scrollBar->setValue(0);

}
//批量添加数据点
void WaveformChart::addData1Points(QList<int>x,QList<double>y)
{
    int len=x.length();
    for(int i=0;i<len;i++)
        series->append(x.at(i),y.at(i));
    chart->update();
    scrollBar->setRange(0, len-_SampleRate*10);
    scrollBar->setValue(0);

}

void WaveformChart::addData2Points(QList<int> x, QList<double> y)
{
    int len=x.length();
    for(int i=0;i<len;i++)
        series_f1->append(x.at(i),y.at(i));
    chart->update();
}

void WaveformChart::addData3Points(QList<int> x, QList<double> y)
{
    int len=x.length();
    for(int i=0;i<len;i++)
        series_f2->append(x.at(i),y.at(i));
    chart->update();
}

// 事件过滤器：捕获鼠标事件
bool WaveformChart::eventFilter(QObject *obj, QEvent *event) {
    if (obj == chartView->viewport()) {
        switch (event->type()) {
        case QEvent::MouseButtonDblClick:{
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            QPointF mousePos = mouseEvent->pos();
            // 将鼠标位置转换为图表坐标
            QPointF chartPos = chartView->chart()->mapToValue(mousePos);

            // 显示坐标值
            QString tooltipText = QString("X: %1, Y: %2").arg(chartPos.x()).arg(chartPos.y());
            qDebug()<<"chartPos.x="<<chartPos.x()<<"chartPos.y="<<chartPos.y();
            // QToolTip::showText(mouseEvent->globalPos(), tooltipText, this);

            // 调用父类的 mousePressEvent
            QChartView::mousePressEvent(mouseEvent);
            break;
        }
        case QEvent::MouseButtonPress: {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton) {
                selectionStart = mouseEvent->pos();
                rubberBand->setGeometry(QRect(selectionStart, QSize()));
                rubberBand->show();
            }
            if(mouseEvent->button() ==Qt::RightButton)
            {
                QPointF mousePos = mouseEvent->pos();
                // 将鼠标位置转换为图表坐标
                QPointF chartPos = chartView->chart()->mapToValue(mousePos);

                QPointF nearestPoint;
                qreal minDistance = std::numeric_limits<qreal>::max();
                for (const QPointF& point : series->points()) {
                    qreal distance = QLineF(mousePos, chartView->chart()->mapToPosition(point)).length();
                    if (distance < minDistance) {
                        minDistance = distance;
                        nearestPoint = point;
                    }
                }
                // series->removePoints(chartPos.x()-1,1);
                // series->insert()
                qDebug()<<"chartPos.x="<<chartPos.x()<<"chartPos.y="<<chartPos.y()<<"xAxis->max()="<<xAxis->max()<<"xAxis->min()"<<xAxis->min();
                qDebug()<<"chartPos.x="<<chartPos.x()<<"nearestPoint"<<nearestPoint.x();
            }
            break;
        }
        case QEvent::MouseMove: {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->buttons() & Qt::LeftButton) {
                rubberBand->setGeometry(QRect(selectionStart, mouseEvent->pos()).normalized());
            }
            break;
        }
        case QEvent::MouseButtonRelease: {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton) {
                rubberBand->hide();
                QRect selectionRect = rubberBand->geometry();

                // 将屏幕坐标转换为图表坐标
                QPointF startPoint = chartView->chart()->mapToValue(selectionRect.topLeft());
                QPointF endPoint = chartView->chart()->mapToValue(selectionRect.bottomRight());

                // 调整 X 轴和 Y 轴的范围
                // qDebug()<<"Point"<<endPoint.x()-startPoint.x()<<"y="<<endPoint.y()-startPoint.y();
                if((endPoint.x()-startPoint.x())>10 && (endPoint.y()-startPoint.y())<-0.50){
                    xAxis->setRange(startPoint.x(), endPoint.x());
                    yAxis->setRange(startPoint.y(), endPoint.y());
                }

            }
            break;
        }
        default:
            break;
        }
    }
    return QWidget::eventFilter(obj, event);
}

// 滚动条值改变事件
void WaveformChart::onScrollBarValueChanged(int value) {
    double range = xAxis->max() - xAxis->min();
    scrollBar->setRange(0, SampleNum-range);
    xAxis->setRange(value, value + range);
}

void WaveformChart::onclicked()
{
    xAxis->setRange(0,SampleNum);
    yAxis->setRange(minv-fabs(minv)/10, maxv+fabs(maxv)/10);
    scrollBar->setRange(0, SampleNum-10*_SampleRate);
}
void WaveformChart::onColorButtonClicked()
{
    QColor color = QColorDialog::getColor(Qt::black, this, "选择曲线颜色");
    if (color.isValid())  {
        QPen pen = series->pen();
        pen.setColor(color);
        series->setPen(pen);
    }
}
